var express = require('express');
var fs = require('fs');
app = express();


var options = {
    key: fs.readFileSync("./ssh_key.pem"),   //加载https证书
    cert: fs.readFileSync("./ssh_cert.pem")

};


server = require('https').createServer(options, app);
//server = require('http').createServer( app);

server.listen(process.env.PORT || 3000);

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/webrtc.html');
});

app.get('/jquery.js', function (req, res) {
    res.sendfile(__dirname + '/jquery.js');
});

app.use(express.static(__dirname + '/'));


var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ server: server });

// 存储socket的数组，这里只能有2个socket，每次测试需要重启，否则会出错
var wsc = [];



// 有socket连入
wss.on('connection', function (ws) {
    console.log('some one connection');

    if (wsc.length >= 2) return;

    // 将socket存入数组
    wsc.push(ws);

    // 记下对方socket在数组中的下标，因为这个测试程序只允许2个socket
    // 所以第一个连入的socket存入0，第二个连入的就是存入1
    // otherIndex就反着来，第一个socket的otherIndex下标为1，第二个socket的otherIndex下标为0



    // 转发收到的消息
    ws.on('message', function (message) {
        //var json = JSON.parse(message);
        for (var i = 0; i < wsc.length; i++) {
            if (wsc[i] && wsc[i] != ws) {


                wsc[i].send(message, function (error) {
                    if (error) {
                        //console.log('Send message error (' + desc + '): ', error);
                    }
                });
            }
        }
    });


    ws.on('close', function () {

        wsc.splice(wsc.indexOf(ws), 1);

        console.log('...........left :' + wsc.length);
    })

    ws.on('error', function () {

        wsc.splice(wsc.indexOf(ws), 1);

        console.log('...........error :' + wsc.length);
    })


});













